using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using System.Net;
using System.IO;
using System.Xml;
using System.Web.Services.Protocols;

/// <summary>
/// Summary description for Util
/// </summary>
public sealed class Util
{
    private static String _authConfigMode;
    private static String _authenticatorType;
    private static String _samlArtifactCookieName;
    private static String _assertionArtifact;
    private static UserDetails _userDetails;

	public Util()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static string authConfigMode
    {
        
        set { _authConfigMode = value; }
        
        get { return _authConfigMode; }
    }

    public static string authenticatorType
    {
        
        set { _authenticatorType = value; }
        
        get { return _authenticatorType; }
    }

    public static string samlArtifactCookieName
    {
        
        set { _samlArtifactCookieName = value; }
        
        get { return _samlArtifactCookieName; }
    }

    public static string assertionArtifact
    {
         set { _assertionArtifact = value; }
        
        get { return _assertionArtifact; }
    }

    public static UserDetails userDetails
    {
        
        set { _userDetails = value; }
        
        get { return _userDetails; }
    }


    public static void ShowPopUpMsg(string msg,Page page,Type type)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("alert('");
        sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
        sb.Append("');");
        ScriptManager.RegisterStartupScript(page, type, "showalert", sb.ToString(), true);
        
    }

    public static String readfromResponse(HttpWebResponse response)
    {
        String target = String.Empty;
        try
        {
            StreamReader streamReader = new StreamReader(response.GetResponseStream(), true);
            try
            {
                target = streamReader.ReadToEnd();
            }
            finally
            {
                streamReader.Close();
            }
        }
        finally
        {
            response.Close();
        }
        return target;
    }

    public static void insertUserinfointoSAMLRequest(String username, String password)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(RequestXML.samlrequest);

        //SET USERNAME
        XmlNode xmlnode = xmldoc.SelectSingleNode(".//*[local-name()='Username']");
        xmlnode.InnerText = username;
        
        //SET PASSWORD
        xmlnode = xmldoc.SelectSingleNode(".//*[local-name()='Password']");
        xmlnode.InnerText = password;

        //SET NameIdentifier 
        xmlnode = xmldoc.SelectSingleNode(".//*[local-name()='NameIdentifier']");
        xmlnode.InnerText = username;

        //UPDATE samlrequest XML
        RequestXML.samlrequest = xmldoc.InnerXml;
        assertionArtifact = "";
    }

    public static bool tryParseXml(string xml)
    {
        try
        {
             XmlDocument xmldoc = new XmlDocument();
             xmldoc.LoadXml(xml);
             return true;
        }
        catch(XmlException e)
        {
            return false;
        }
    }

    //http://www.xignite.com/Support/FAQ.aspx?faqtype=Development&faqcat=Tips&faqitem=TIP002
    public static CookieContainer getCookieContainer()
    {
        System.Net.Cookie objCookie = new System.Net.Cookie(Util.samlArtifactCookieName, Util.assertionArtifact, "/", Constants.domainname);
        System.Net.CookieContainer objCookieContainer = new System.Net.CookieContainer();
        objCookieContainer.Add(objCookie);
        return objCookieContainer;
    }

    public static String run(String request)
    {
        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(request);
        String soapResult = CallWebService(soapEnvelopeXml);
        return soapResult;
    }

    public static String CallWebService(XmlDocument soapEnvelopeXml)
    {
        String _url = Constants.cordysurl + "/com.eibus.web.soap.Gateway.wcp";
        String _action = "";


        HttpWebRequest webRequest = CreateWebRequest(_url, _action);
        webRequest.Headers.Add("Cookie", Util.samlArtifactCookieName + "=" + Util.assertionArtifact);
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
        
        // begin async call to web request.
        IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

        // suspend this thread until call is complete. You might want to
        // do something usefull here like update your UI.
        asyncResult.AsyncWaitHandle.WaitOne();

        // get the response from the completed web request.
        string soapResult=String.Empty;
        try
        {
            using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
            {
                soapResult = rd.ReadToEnd();
            }
        }
        catch (WebException wex)
        {
            /*LOGIN FAILED : WRONG USERNAME OR PASSWORD
             * if (wex.Status == WebExceptionStatus.ProtocolError)
            {
                return wex.Message;
            }*/

            return wex.Message;
        }
        
        return soapResult;

    }

    private static HttpWebRequest CreateWebRequest(string url, string action)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Accept = "*/*";
        webRequest.ContentType = "text/xml;charset=\"utf-8\"";
        //webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
        webRequest.Method = "POST";
        return webRequest;
    }

    private static XmlDocument CreateSoapEnvelope(String requestXML)
    {
        XmlDocument soapEnvelop = new XmlDocument();
        soapEnvelop.LoadXml(requestXML);
        return soapEnvelop;
    }

    private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
    {
        using (Stream stream = webRequest.GetRequestStream())
        {
            soapEnvelopeXml.Save(stream);
        }
    }
}
